package MoviePack;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;
import java.util.ArrayList;

public class MovieLister implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1353374764022067132L;
	private IMovieFinder movieFinder;
	private Object[] movieArray;
	private PropertyChangeSupport changes;

	public MovieLister() {
		changes = new PropertyChangeSupport(this);
		this.movieFinder = new XMLMovieFinder();
	}

	public void moviesDirectedBy(String director) {
		ArrayList<Movie> allMovies = this.movieFinder.findall();
		ArrayList<Movie> filteredMovies = new ArrayList<Movie>();

		for (int i = 0; i < allMovies.size(); i++) {
			if (allMovies.get(i).getDirector().equals(director)) {
				filteredMovies.add(allMovies.get(i));
			}
		}

		setMovieArray(filteredMovies.toArray(new Movie[filteredMovies.size()]));

		Object[] oldMovies = null;
		if (this.getMovieArray() != null) {
			oldMovies = this.getMovieArray().clone();
		}

		changes.firePropertyChange("foundMovies", oldMovies, this.getMovieArray());
	}

	public void setMovieArray(Object[] movieArray) {
		this.movieArray = movieArray;
	}

	public Object[] getMovieArray() {
		return movieArray;
	}

	public void setMovieFinder(IMovieFinder movieFinder) {
		this.movieFinder = movieFinder;
	}

	public void addPropertyChangeListener(PropertyChangeListener listener) {
		this.changes.addPropertyChangeListener(listener);
	}

	public void removePropertyChangeListener(PropertyChangeListener listener) {
		this.changes.removePropertyChangeListener(listener);
	}

	@Override
	public String toString() {
		String tmpStr = "";

		if (movieArray != null) {
			for (int i = 0; i < movieArray.length; i++) {
				tmpStr += ((Movie) movieArray[i]).toString();
			}
		}
		return tmpStr;
	}

}
